/*
 * @lc app=leetcode.cn id=92 lang=java
 *
 * [92] 反转链表 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        if (head == null) {
            return null;
        }

        ListNode dummy = new ListNode(-1, head);
        ListNode cur = dummy;
        ListNode in, out;

        for (int i = 0; i < left - 1; i++) {
            cur = cur.next;
        }
        in = cur;
        for (int i = 0; i < right - left + 1; i++) {
            cur = cur.next;
        }
        out = cur.next;
        cur.next = null;

        ListNode reversedPart = reverseList(in.next);
        in.next = reversedPart;
        cur = reversedPart;
        while (cur.next != null) {
            cur = cur.next;
        }
        cur.next = out;

        return dummy.next;
    }

    public ListNode reverseList(ListNode head) {
        ListNode cur = head;
        ListNode prev = null;
        
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }

        return prev;
    }
}
// @lc code=end

